<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
  <meta name="theme-color" content="#222">
  <meta name="generator" content="Hexo 5.4.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

  <link rel="stylesheet" href="/css/main.css">



  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.2/css/all.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

  <script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {
      "hostname": "holidaypenguin.gitee.io",
      "root": "/",
      "images": "/images",
      "scheme": "Mist",
      "version": "8.2.2",
      "exturl": false,
      "sidebar": {
        "position": "right",
        "display": "always",
        "padding": 18,
        "offset": 12
      },
      "copycode": true,
      "bookmark": {
        "enable": false,
        "color": "#222",
        "save": "auto"
      },
      "fancybox": false,
      "mediumzoom": false,
      "lazyload": false,
      "pangu": false,
      "comments": {
        "style": "tabs",
        "active": null,
        "storage": true,
        "lazyload": false,
        "nav": null
      },
      "motion": {
        "enable": true,
        "async": true,
        "transition": {
          "post_block": "fadeIn",
          "post_header": "fadeInDown",
          "post_body": "fadeInDown",
          "coll_header": "fadeInLeft",
          "sidebar": "slideUpIn"
        }
      },
      "prism": false,
      "i18n": {
        "placeholder": "搜索...",
        "empty": "没有找到任何搜索结果：${query}",
        "hits_time": "找到 ${hits} 个搜索结果（用时 ${time} 毫秒）",
        "hits": "找到 ${hits} 个搜索结果"
      },
      "path": "/search.xml",
      "localsearch": {
        "enable": true,
        "trigger": "auto",
        "top_n_per_article": 1,
        "unescape": false,
        "preload": false
      }
    };
  </script>
  <meta property="og:type" content="article">
  <meta property="og:title" content="JavaScript 复杂判断的更优雅写法">
  <meta property="og:url" content="https://holidaypenguin.gitee.io/blob/2019-05-21-more-elegant-writing-of-javascript-complex-judgments/index.html">
  <meta property="og:site_name" content="HolidayPenguin">
  <meta property="og:locale" content="zh_CN">
  <meta property="article:published_time" content="2019-05-21T12:28:41.000Z">
  <meta property="article:modified_time" content="2019-05-21T12:28:41.000Z">
  <meta property="article:author" content="holidaypenguin">
  <meta property="article:tag" content="JavaScript">
  <meta property="article:tag" content="复杂判断">
  <meta name="twitter:card" content="summary">


  <link rel="canonical" href="https://holidaypenguin.gitee.io/blob/2019-05-21-more-elegant-writing-of-javascript-complex-judgments/">


  <script class="page-configurations">
    // https://hexo.io/docs/variables.html
    CONFIG.page = {
      sidebar: "",
      isHome: false,
      isPost: true,
      lang: 'zh-CN'
    };
  </script>
  <title>JavaScript 复杂判断的更优雅写法 | HolidayPenguin</title>





  <noscript>
    <style>
      body {
        margin-top: 2rem;
      }

      .use-motion .menu-item,
      .use-motion .sidebar,
      .use-motion .post-block,
      .use-motion .pagination,
      .use-motion .comments,
      .use-motion .post-header,
      .use-motion .post-body,
      .use-motion .collection-header {
        visibility: visible;
      }

      .use-motion .header,
      .use-motion .site-brand-container .toggle,
      .use-motion .footer {
        opacity: initial;
      }

      .use-motion .site-title,
      .use-motion .site-subtitle,
      .use-motion .custom-logo-image {
        opacity: initial;
        top: initial;
      }

      .use-motion .logo-line {
        transform: scaleX(1);
      }

      .search-pop-overlay,
      .sidebar-nav {
        display: none;
      }

      .sidebar-panel {
        display: block;
      }
    </style>
  </noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner">
        <div class="site-brand-container">
          <div class="site-nav-toggle">
            <div class="toggle" aria-label="切换导航栏" role="button">
              <span class="toggle-line"></span>
              <span class="toggle-line"></span>
              <span class="toggle-line"></span>
            </div>
          </div>

          <div class="site-meta">

            <a href="/" class="brand" rel="start">
              <i class="logo-line"></i>
              <h1 class="site-title">HolidayPenguin</h1>
              <i class="logo-line"></i>
            </a>
          </div>

          <div class="site-nav-right">
            <div class="toggle popup-trigger">
              <i class="fa fa-search fa-fw fa-lg"></i>
            </div>
          </div>
        </div>



        <nav class="site-nav">
          <ul class="main-menu menu">
            <li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li>
            <li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li>
            <li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li>
            <li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li>
            <li class="menu-item menu-item-search">
              <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
              </a>
            </li>
          </ul>
        </nav>



        <div class="search-pop-overlay">
          <div class="popup search-popup">
            <div class="search-header">
              <span class="search-icon">
                <i class="fa fa-search"></i>
              </span>
              <div class="search-input-container">
                <input autocomplete="off" autocapitalize="off" maxlength="80" placeholder="搜索..." spellcheck="false" type="search" class="search-input">
              </div>
              <span class="popup-btn-close" role="button">
                <i class="fa fa-times-circle"></i>
              </span>
            </div>
            <div class="search-result-container no-result">
              <div class="search-result-icon">
                <i class="fa fa-spinner fa-pulse fa-5x"></i>
              </div>
            </div>

          </div>
        </div>

      </div>


      <div class="toggle sidebar-toggle" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
      </div>

      <aside class="sidebar">

        <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
          <ul class="sidebar-nav">
            <li class="sidebar-nav-toc">
              文章目录
            </li>
            <li class="sidebar-nav-overview">
              站点概览
            </li>
          </ul>

          <div class="sidebar-panel-container">
            <!--noindex-->
            <div class="post-toc-wrap sidebar-panel">
              <div class="post-toc animated">
                <ol class="nav">
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#if-else"><span class="nav-number">1.</span> <span class="nav-text">if&#x2F;else</span></a></li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#switch"><span class="nav-number">2.</span> <span class="nav-text">switch</span></a></li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%80%E5%85%83%E5%88%A4%E6%96%AD%E6%97%B6%EF%BC%9A%E5%AD%98%E5%88%B0Object%E9%87%8C"><span class="nav-number">3.</span> <span class="nav-text">一元判断时：存到Object里</span></a></li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%80%E5%85%83%E5%88%A4%E6%96%AD%E6%97%B6%EF%BC%9A%E5%AD%98%E5%88%B0Map%E9%87%8C"><span class="nav-number">4.</span> <span class="nav-text">一元判断时：存到Map里</span></a></li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%A4%9A%E5%85%83%E5%88%A4%E6%96%AD%E6%97%B6%EF%BC%9A%E5%B0%86condition%E6%8B%BC%E6%8E%A5%E6%88%90%E5%AD%97%E7%AC%A6%E4%B8%B2%E5%AD%98%E5%88%B0Map%E9%87%8C"><span class="nav-number">5.</span> <span class="nav-text">多元判断时：将condition拼接成字符串存到Map里</span></a></li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%A4%9A%E5%85%83%E5%88%A4%E6%96%AD%E6%97%B6%EF%BC%9A%E5%B0%86condition%E6%8B%BC%E6%8E%A5%E6%88%90%E5%AD%97%E7%AC%A6%E4%B8%B2%E5%AD%98%E5%88%B0Object%E9%87%8C"><span class="nav-number">6.</span> <span class="nav-text">多元判断时：将condition拼接成字符串存到Object里</span></a></li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%A4%9A%E5%85%83%E5%88%A4%E6%96%AD%E6%97%B6%EF%BC%9A%E5%B0%86condition%E5%AD%98%E4%B8%BAObject%E5%AD%98%E5%88%B0Map%E9%87%8C"><span class="nav-number">7.</span> <span class="nav-text">多元判断时：将condition存为Object存到Map里</span></a></li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%A4%9A%E5%85%83%E5%88%A4%E6%96%AD%E6%97%B6%EF%BC%9A%E5%B0%86condition%E5%86%99%E4%BD%9C%E6%AD%A3%E5%88%99%E5%AD%98%E5%88%B0Map%E9%87%8C"><span class="nav-number">8.</span> <span class="nav-text">多元判断时：将condition写作正则存到Map里</span></a></li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%80%BB%E7%BB%93"><span class="nav-number">9.</span> <span class="nav-text">总结</span></a></li>
                </ol>
                </li>
                <li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%8F%82%E8%80%83"><span class="nav-number"></span> <span class="nav-text">参考</span></a>
              </div>
            </div>
            <!--/noindex-->

            <div class="site-overview-wrap sidebar-panel">
              <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
                <p class="site-author-name" itemprop="name">holidaypenguin</p>
                <div class="site-description" itemprop="description"></div>
              </div>
              <div class="site-state-wrap site-overview-item animated">
                <nav class="site-state">
                  <div class="site-state-item site-state-posts">
                    <a href="/archives/">

                      <span class="site-state-item-count">138</span>
                      <span class="site-state-item-name">日志</span>
                    </a>
                  </div>
                  <div class="site-state-item site-state-categories">
                    <a href="/categories/">

                      <span class="site-state-item-count">26</span>
                      <span class="site-state-item-name">分类</span></a>
                  </div>
                  <div class="site-state-item site-state-tags">
                    <a href="/tags/">

                      <span class="site-state-item-count">234</span>
                      <span class="site-state-item-name">标签</span></a>
                  </div>
                </nav>
              </div>
              <div class="links-of-author site-overview-item animated">
                <span class="links-of-author-item">
                  <a href="https://github.com/holidaypenguin" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;holidaypenguin" rel="noopener" target="_blank"><i class="github fa-fw"></i>GitHub</a>
                </span>
                <span class="links-of-author-item">
                  <a href="mailto:songshipeng2016@gmail.com" title="E-Mail → mailto:songshipeng2016@gmail.com" rel="noopener" target="_blank"><i class="envelope fa-fw"></i>E-Mail</a>
                </span>
              </div>



            </div>
          </div>
        </div>
      </aside>
      <div class="sidebar-dimmer"></div>


    </header>


    <div class="back-to-top" role="button">
      <i class="fa fa-arrow-up"></i>
      <span>0%</span>
    </div>

    <noscript>
      <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
    </noscript>


    <div class="main-inner post posts-expand">





      <div class="post-block">



        <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
          <link itemprop="mainEntityOfPage" href="https://holidaypenguin.gitee.io/blob/2019-05-21-more-elegant-writing-of-javascript-complex-judgments/">

          <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
            <meta itemprop="image" content="/images/avatar.gif">
            <meta itemprop="name" content="holidaypenguin">
            <meta itemprop="description" content="">
          </span>

          <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
            <meta itemprop="name" content="HolidayPenguin">
          </span>
          <header class="post-header">
            <h1 class="post-title" itemprop="name headline">
              JavaScript 复杂判断的更优雅写法
            </h1>

            <div class="post-meta-container">
              <div class="post-meta">
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-calendar"></i>
                  </span>
                  <span class="post-meta-item-text">发表于</span>

                  <time title="创建时间：2019-05-21 20:28:41" itemprop="dateCreated datePublished" datetime="2019-05-21T20:28:41+08:00">2019-05-21</time>
                </span>
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-folder"></i>
                  </span>
                  <span class="post-meta-item-text">分类于</span>
                  <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                    <a href="/categories/JavaScript/" itemprop="url" rel="index"><span itemprop="name">JavaScript</span></a>
                  </span>
                </span>


                <span id="/blob/2019-05-21-more-elegant-writing-of-javascript-complex-judgments/" class="post-meta-item leancloud_visitors" data-flag-title="JavaScript 复杂判断的更优雅写法" title="阅读次数">
                  <span class="post-meta-item-icon">
                    <i class="far fa-eye"></i>
                  </span>
                  <span class="post-meta-item-text">阅读次数：</span>
                  <span class="leancloud-visitors-count"></span>
                </span>
              </div>

              <div class="post-description">
                <!-- more -->
              </div>
            </div>
          </header>




          <div class="post-body" itemprop="articleBody">
            <p>本文系转载（<a target="_blank" rel="noopener" href="https://juejin.im/post/5bdfef86e51d453bf8051bf8%EF%BC%89">https://juejin.im/post/5bdfef86e51d453bf8051bf8）</a></p>
            <p><strong>前提</strong></p>
            <p>我们编写js代码时经常遇到复杂逻辑判断的情况，通常大家可以用if/else或者switch来实现多个条件判断，但这样会有个问题，随着逻辑复杂度的增加，代码中的if/else/switch会变得越来越臃肿，越来越看不懂，那么如何更优雅的写判断逻辑，本文带你试一下。</p>
            <p>下面就举例说明</p>
            <h2 id="if-else"><a href="#if-else" class="headerlink" title="if/else"></a>if/else</h2>
            <p>先看一段代码</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 按钮点击事件</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;number&#125;</span> </span>status 活动状态：1 开团进行中 2 开团失败 3 商品售罄 4 开团成功 5 系统取消</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">const</span> onButtonClick = <span class="function">(<span class="params">status</span>)=&gt;</span>&#123;</span><br><span class="line">  <span class="keyword">if</span>(status == <span class="number">1</span>)&#123;</span><br><span class="line">    sendLog(<span class="string">&#x27;processing&#x27;</span>)</span><br><span class="line">    jumpTo(<span class="string">&#x27;IndexPage&#x27;</span>)</span><br><span class="line">  &#125;<span class="keyword">else</span> <span class="keyword">if</span>(status == <span class="number">2</span>)&#123;</span><br><span class="line">    sendLog(<span class="string">&#x27;fail&#x27;</span>)</span><br><span class="line">    jumpTo(<span class="string">&#x27;FailPage&#x27;</span>)</span><br><span class="line">  &#125;<span class="keyword">else</span> <span class="keyword">if</span>(status == <span class="number">3</span>)&#123;</span><br><span class="line">    sendLog(<span class="string">&#x27;fail&#x27;</span>)</span><br><span class="line">    jumpTo(<span class="string">&#x27;FailPage&#x27;</span>)</span><br><span class="line">  &#125;<span class="keyword">else</span> <span class="keyword">if</span>(status == <span class="number">4</span>)&#123;</span><br><span class="line">    sendLog(<span class="string">&#x27;success&#x27;</span>)</span><br><span class="line">    jumpTo(<span class="string">&#x27;SuccessPage&#x27;</span>)</span><br><span class="line">  &#125;<span class="keyword">else</span> <span class="keyword">if</span>(status == <span class="number">5</span>)&#123;</span><br><span class="line">    sendLog(<span class="string">&#x27;cancel&#x27;</span>)</span><br><span class="line">    jumpTo(<span class="string">&#x27;CancelPage&#x27;</span>)</span><br><span class="line">  &#125;<span class="keyword">else</span> &#123;</span><br><span class="line">    sendLog(<span class="string">&#x27;other&#x27;</span>)</span><br><span class="line">    jumpTo(<span class="string">&#x27;Index&#x27;</span>)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>通过代码可以看到这个按钮的点击逻辑：根据不同活动状态做两件事情，发送日志埋点和跳转到对应页面，</p>
            <h2 id="switch"><a href="#switch" class="headerlink" title="switch"></a>switch</h2>
            <p>大家可以很轻易的提出这段代码的改写方案，switch出场：</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 按钮点击事件</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;number&#125;</span> </span>status 活动状态：1 开团进行中 2 开团失败 3 商品售罄 4 开团成功 5 系统取消</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">const</span> onButtonClick = <span class="function">(<span class="params">status</span>)=&gt;</span>&#123;</span><br><span class="line">  <span class="keyword">switch</span> (status)&#123;</span><br><span class="line">    <span class="keyword">case</span> <span class="number">1</span>:</span><br><span class="line">      sendLog(<span class="string">&#x27;processing&#x27;</span>)</span><br><span class="line">      jumpTo(<span class="string">&#x27;IndexPage&#x27;</span>)</span><br><span class="line">      <span class="keyword">break</span></span><br><span class="line">    <span class="keyword">case</span> <span class="number">2</span>:</span><br><span class="line">    <span class="keyword">case</span> <span class="number">3</span>:</span><br><span class="line">      sendLog(<span class="string">&#x27;fail&#x27;</span>)</span><br><span class="line">      jumpTo(<span class="string">&#x27;FailPage&#x27;</span>)</span><br><span class="line">      <span class="keyword">break</span>  </span><br><span class="line">    <span class="keyword">case</span> <span class="number">4</span>:</span><br><span class="line">      sendLog(<span class="string">&#x27;success&#x27;</span>)</span><br><span class="line">      jumpTo(<span class="string">&#x27;SuccessPage&#x27;</span>)</span><br><span class="line">      <span class="keyword">break</span></span><br><span class="line">    <span class="keyword">case</span> <span class="number">5</span>:</span><br><span class="line">      sendLog(<span class="string">&#x27;cancel&#x27;</span>)</span><br><span class="line">      jumpTo(<span class="string">&#x27;CancelPage&#x27;</span>)</span><br><span class="line">      <span class="keyword">break</span></span><br><span class="line">    <span class="keyword">default</span>:</span><br><span class="line">      sendLog(<span class="string">&#x27;other&#x27;</span>)</span><br><span class="line">      jumpTo(<span class="string">&#x27;Index&#x27;</span>)</span><br><span class="line">      <span class="keyword">break</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>嗯，这样看起来比if/else清晰多了，细心的同学也发现了小技巧，case 2和case 3逻辑一样的时候，可以省去执行语句和break，则case 2的情况自动执行case 3的逻辑。</p>
            <h2 id="一元判断时：存到Object里"><a href="#一元判断时：存到Object里" class="headerlink" title="一元判断时：存到Object里"></a>一元判断时：存到Object里</h2>
            <p>这时有同学会说，还有更简单的写法：</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="keyword">const</span> actions = &#123;</span><br><span class="line">  <span class="string">&#x27;1&#x27;</span>: [<span class="string">&#x27;processing&#x27;</span>,<span class="string">&#x27;IndexPage&#x27;</span>],</span><br><span class="line">  <span class="string">&#x27;2&#x27;</span>: [<span class="string">&#x27;fail&#x27;</span>,<span class="string">&#x27;FailPage&#x27;</span>],</span><br><span class="line">  <span class="string">&#x27;3&#x27;</span>: [<span class="string">&#x27;fail&#x27;</span>,<span class="string">&#x27;FailPage&#x27;</span>],</span><br><span class="line">  <span class="string">&#x27;4&#x27;</span>: [<span class="string">&#x27;success&#x27;</span>,<span class="string">&#x27;SuccessPage&#x27;</span>],</span><br><span class="line">  <span class="string">&#x27;5&#x27;</span>: [<span class="string">&#x27;cancel&#x27;</span>,<span class="string">&#x27;CancelPage&#x27;</span>],</span><br><span class="line">  <span class="string">&#x27;default&#x27;</span>: [<span class="string">&#x27;other&#x27;</span>,<span class="string">&#x27;Index&#x27;</span>],</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 按钮点击事件</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;number&#125;</span> </span>status 活动状态：1开团进行中 2开团失败 3 商品售罄 4 开团成功 5 系统取消</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">const</span> onButtonClick = <span class="function">(<span class="params">status</span>)=&gt;</span>&#123;</span><br><span class="line">  <span class="keyword">let</span> action = actions[status] || actions[<span class="string">&#x27;default&#x27;</span>],</span><br><span class="line">      logName = action[<span class="number">0</span>],</span><br><span class="line">      pageName = action[<span class="number">1</span>]</span><br><span class="line">  sendLog(logName)</span><br><span class="line">  jumpTo(pageName)</span><br><span class="line">&#125;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>上面代码确实看起来更清爽了，这种方法的聪明之处在于：将判断条件作为对象的属性名，将处理逻辑作为对象的属性值，在按钮点击的时候，通过对象属性查找的方式来进行逻辑判断，这种写法特别适合一元条件判断的情况。</p>
            <h2 id="一元判断时：存到Map里"><a href="#一元判断时：存到Map里" class="headerlink" title="一元判断时：存到Map里"></a>一元判断时：存到Map里</h2>
            <p>是不是还有其他写法呢？有的：</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="keyword">const</span> actions = <span class="keyword">new</span> <span class="built_in">Map</span>([</span><br><span class="line">  [<span class="number">1</span>, [<span class="string">&#x27;processing&#x27;</span>,<span class="string">&#x27;IndexPage&#x27;</span>]],</span><br><span class="line">  [<span class="number">2</span>, [<span class="string">&#x27;fail&#x27;</span>,<span class="string">&#x27;FailPage&#x27;</span>]],</span><br><span class="line">  [<span class="number">3</span>, [<span class="string">&#x27;fail&#x27;</span>,<span class="string">&#x27;FailPage&#x27;</span>]],</span><br><span class="line">  [<span class="number">4</span>, [<span class="string">&#x27;success&#x27;</span>,<span class="string">&#x27;SuccessPage&#x27;</span>]],</span><br><span class="line">  [<span class="number">5</span>, [<span class="string">&#x27;cancel&#x27;</span>,<span class="string">&#x27;CancelPage&#x27;</span>]],</span><br><span class="line">  [<span class="string">&#x27;default&#x27;</span>, [<span class="string">&#x27;other&#x27;</span>,<span class="string">&#x27;Index&#x27;</span>]]</span><br><span class="line">])</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 按钮点击事件</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;number&#125;</span> </span>status 活动状态：1 开团进行中 2 开团失败 3 商品售罄 4 开团成功 5 系统取消</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">const</span> onButtonClick = <span class="function">(<span class="params">status</span>)=&gt;</span>&#123;</span><br><span class="line">  <span class="keyword">let</span> action = actions.get(status) || actions.get(<span class="string">&#x27;default&#x27;</span>)</span><br><span class="line">  sendLog(action[<span class="number">0</span>])</span><br><span class="line">  jumpTo(action[<span class="number">1</span>])</span><br><span class="line">&#125;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>这样写用到了es6里的Map对象，是不是更爽了？Map对象和Object对象有什么区别呢？</p>
            <ol>
              <li>一个对象通常都有自己的原型，所以一个对象总有一个”prototype”键。</li>
              <li>一个对象的键只能是字符串或者Symbols，但一个Map的键可以是任意值。</li>
              <li>你可以通过size属性很容易地得到一个Map的键值对个数，而对象的键值对个数只能手动确认。</li>
            </ol>
            <h2 id="多元判断时：将condition拼接成字符串存到Map里"><a href="#多元判断时：将condition拼接成字符串存到Map里" class="headerlink" title="多元判断时：将condition拼接成字符串存到Map里"></a>多元判断时：将condition拼接成字符串存到Map里</h2>
            <p>我们需要把问题升级一下，以前按钮点击时候只需要判断status，现在还需要判断用户的身份：</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 按钮点击事件</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;number&#125;</span> </span>status 活动状态：1开团进行中 2开团失败 3 开团成功 4 商品售罄 5 有库存未开团</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;string&#125;</span> </span>identity 身份标识：guest客态 master主态</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">const</span> onButtonClick = <span class="function">(<span class="params">status,identity</span>)=&gt;</span>&#123;</span><br><span class="line">  <span class="keyword">if</span>(identity == <span class="string">&#x27;guest&#x27;</span>)&#123;</span><br><span class="line">    <span class="keyword">if</span>(status == <span class="number">1</span>)&#123;</span><br><span class="line">      <span class="comment">//do sth</span></span><br><span class="line">    &#125;<span class="keyword">else</span> <span class="keyword">if</span>(status == <span class="number">2</span>)&#123;</span><br><span class="line">      <span class="comment">//do sth</span></span><br><span class="line">    &#125;<span class="keyword">else</span> <span class="keyword">if</span>(status == <span class="number">3</span>)&#123;</span><br><span class="line">      <span class="comment">//do sth</span></span><br><span class="line">    &#125;<span class="keyword">else</span> <span class="keyword">if</span>(status == <span class="number">4</span>)&#123;</span><br><span class="line">      <span class="comment">//do sth</span></span><br><span class="line">    &#125;<span class="keyword">else</span> <span class="keyword">if</span>(status == <span class="number">5</span>)&#123;</span><br><span class="line">      <span class="comment">//do sth</span></span><br><span class="line">    &#125;<span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="comment">//do sth</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;<span class="keyword">else</span> <span class="keyword">if</span>(identity == <span class="string">&#x27;master&#x27;</span>) &#123;</span><br><span class="line">    <span class="keyword">if</span>(status == <span class="number">1</span>)&#123;</span><br><span class="line">      <span class="comment">//do sth</span></span><br><span class="line">    &#125;<span class="keyword">else</span> <span class="keyword">if</span>(status == <span class="number">2</span>)&#123;</span><br><span class="line">      <span class="comment">//do sth</span></span><br><span class="line">    &#125;<span class="keyword">else</span> <span class="keyword">if</span>(status == <span class="number">3</span>)&#123;</span><br><span class="line">      <span class="comment">//do sth</span></span><br><span class="line">    &#125;<span class="keyword">else</span> <span class="keyword">if</span>(status == <span class="number">4</span>)&#123;</span><br><span class="line">      <span class="comment">//do sth</span></span><br><span class="line">    &#125;<span class="keyword">else</span> <span class="keyword">if</span>(status == <span class="number">5</span>)&#123;</span><br><span class="line">      <span class="comment">//do sth</span></span><br><span class="line">    &#125;<span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="comment">//do sth</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>原谅我不写每个判断里的具体逻辑了，因为代码太冗长了。</p>
            <p>原谅我又用了if/else，因为我看到很多人依然在用if/else写这种大段的逻辑判断。</p>
            <p>从上面的例子我们可以看到，当你的逻辑升级为二元判断时，你的判断量会加倍，你的代码量也会加倍，这时怎么写更清爽呢？</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="keyword">const</span> actions = <span class="keyword">new</span> <span class="built_in">Map</span>([</span><br><span class="line">  [<span class="string">&#x27;guest_1&#x27;</span>, <span class="function">()=&gt;</span>&#123;<span class="comment">/*do sth*/</span>&#125;],</span><br><span class="line">  [<span class="string">&#x27;guest_2&#x27;</span>, <span class="function">()=&gt;</span>&#123;<span class="comment">/*do sth*/</span>&#125;],</span><br><span class="line">  [<span class="string">&#x27;guest_3&#x27;</span>, <span class="function">()=&gt;</span>&#123;<span class="comment">/*do sth*/</span>&#125;],</span><br><span class="line">  [<span class="string">&#x27;guest_4&#x27;</span>, <span class="function">()=&gt;</span>&#123;<span class="comment">/*do sth*/</span>&#125;],</span><br><span class="line">  [<span class="string">&#x27;guest_5&#x27;</span>, <span class="function">()=&gt;</span>&#123;<span class="comment">/*do sth*/</span>&#125;],</span><br><span class="line">  [<span class="string">&#x27;master_1&#x27;</span>, <span class="function">()=&gt;</span>&#123;<span class="comment">/*do sth*/</span>&#125;],</span><br><span class="line">  [<span class="string">&#x27;master_2&#x27;</span>, <span class="function">()=&gt;</span>&#123;<span class="comment">/*do sth*/</span>&#125;],</span><br><span class="line">  [<span class="string">&#x27;master_3&#x27;</span>, <span class="function">()=&gt;</span>&#123;<span class="comment">/*do sth*/</span>&#125;],</span><br><span class="line">  [<span class="string">&#x27;master_4&#x27;</span>, <span class="function">()=&gt;</span>&#123;<span class="comment">/*do sth*/</span>&#125;],</span><br><span class="line">  [<span class="string">&#x27;master_5&#x27;</span>, <span class="function">()=&gt;</span>&#123;<span class="comment">/*do sth*/</span>&#125;],</span><br><span class="line">  [<span class="string">&#x27;default&#x27;</span>, <span class="function">()=&gt;</span>&#123;<span class="comment">/*do sth*/</span>&#125;],</span><br><span class="line">])</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 按钮点击事件</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;string&#125;</span> </span>identity 身份标识：guest客态 master主态</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;number&#125;</span> </span>status 活动状态：1 开团进行中 2 开团失败 3 开团成功 4 商品售罄 5 有库存未开团</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">const</span> onButtonClick = <span class="function">(<span class="params">identity,status</span>)=&gt;</span>&#123;</span><br><span class="line">  <span class="keyword">let</span> action = actions.get(<span class="string">`<span class="subst">$&#123;identity&#125;</span>_<span class="subst">$&#123;status&#125;</span>`</span>) || actions.get(<span class="string">&#x27;default&#x27;</span>)</span><br><span class="line">  action.call(<span class="built_in">this</span>)</span><br><span class="line">&#125;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>上述代码核心逻辑是：把两个条件拼接成字符串，并通过以条件拼接字符串作为键，以处理函数作为值的Map对象进行查找并执行，这种写法在多元条件判断时候尤其好用。</p>
            <h2 id="多元判断时：将condition拼接成字符串存到Object里"><a href="#多元判断时：将condition拼接成字符串存到Object里" class="headerlink" title="多元判断时：将condition拼接成字符串存到Object里"></a>多元判断时：将condition拼接成字符串存到Object里</h2>
            <p>当然上述代码如果用Object对象来实现也是类似的：</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="keyword">const</span> actions = &#123;</span><br><span class="line">  <span class="string">&#x27;guest_1&#x27;</span>:<span class="function">()=&gt;</span>&#123;<span class="comment">/*do sth*/</span>&#125;,</span><br><span class="line">  <span class="string">&#x27;guest_2&#x27;</span>:<span class="function">()=&gt;</span>&#123;<span class="comment">/*do sth*/</span>&#125;,</span><br><span class="line">  <span class="comment">//....</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> onButtonClick = <span class="function">(<span class="params">identity,status</span>)=&gt;</span>&#123;</span><br><span class="line">  <span class="keyword">let</span> action = actions[<span class="string">`<span class="subst">$&#123;identity&#125;</span>_<span class="subst">$&#123;status&#125;</span>`</span>] || actions[<span class="string">&#x27;default&#x27;</span>]</span><br><span class="line">  action.call(<span class="built_in">this</span>)</span><br><span class="line">&#125;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <h2 id="多元判断时：将condition存为Object存到Map里"><a href="#多元判断时：将condition存为Object存到Map里" class="headerlink" title="多元判断时：将condition存为Object存到Map里"></a>多元判断时：将condition存为Object存到Map里</h2>
            <p>如果有些同学觉得把查询条件拼成字符串有点别扭，那还有一种方案，就是用Map对象，以Object对象作为key：</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="keyword">const</span> actions = <span class="keyword">new</span> <span class="built_in">Map</span>([</span><br><span class="line">  [&#123;<span class="attr">identity</span>:<span class="string">&#x27;guest&#x27;</span>,<span class="attr">status</span>:<span class="number">1</span>&#125;,<span class="function">()=&gt;</span>&#123;<span class="comment">/*do sth*/</span>&#125;],</span><br><span class="line">  [&#123;<span class="attr">identity</span>:<span class="string">&#x27;guest&#x27;</span>,<span class="attr">status</span>:<span class="number">2</span>&#125;,<span class="function">()=&gt;</span>&#123;<span class="comment">/*do sth*/</span>&#125;],</span><br><span class="line">  <span class="comment">//...</span></span><br><span class="line">])</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> onButtonClick = <span class="function">(<span class="params">identity,status</span>)=&gt;</span>&#123;</span><br><span class="line">  <span class="keyword">let</span> action = [...actions].filter(<span class="function">(<span class="params">[key,value]</span>)=&gt;</span>(key.identity == identity &amp;&amp; key.status == status))</span><br><span class="line">  action.forEach(<span class="function">(<span class="params">[key,value]</span>)=&gt;</span>value.call(<span class="built_in">this</span>))</span><br><span class="line">&#125;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>是不是又高级了一点点？</p>
            <p>这里也看出来Map与Object的区别，Map可以用任何类型的数据作为key。</p>
            <h2 id="多元判断时：将condition写作正则存到Map里"><a href="#多元判断时：将condition写作正则存到Map里" class="headerlink" title="多元判断时：将condition写作正则存到Map里"></a>多元判断时：将condition写作正则存到Map里</h2>
            <p>我们现在再将难度升级一点点，假如guest情况下，status1-4的处理逻辑都一样怎么办，最差的情况是这样：</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="keyword">const</span> actions = <span class="keyword">new</span> <span class="built_in">Map</span>([</span><br><span class="line">  [&#123;<span class="attr">identity</span>:<span class="string">&#x27;guest&#x27;</span>,<span class="attr">status</span>:<span class="number">1</span>&#125;,<span class="function">()=&gt;</span>&#123;<span class="comment">/* functionA */</span>&#125;],</span><br><span class="line">  [&#123;<span class="attr">identity</span>:<span class="string">&#x27;guest&#x27;</span>,<span class="attr">status</span>:<span class="number">2</span>&#125;,<span class="function">()=&gt;</span>&#123;<span class="comment">/* functionA */</span>&#125;],</span><br><span class="line">  [&#123;<span class="attr">identity</span>:<span class="string">&#x27;guest&#x27;</span>,<span class="attr">status</span>:<span class="number">3</span>&#125;,<span class="function">()=&gt;</span>&#123;<span class="comment">/* functionA */</span>&#125;],</span><br><span class="line">  [&#123;<span class="attr">identity</span>:<span class="string">&#x27;guest&#x27;</span>,<span class="attr">status</span>:<span class="number">4</span>&#125;,<span class="function">()=&gt;</span>&#123;<span class="comment">/* functionA */</span>&#125;],</span><br><span class="line">  [&#123;<span class="attr">identity</span>:<span class="string">&#x27;guest&#x27;</span>,<span class="attr">status</span>:<span class="number">5</span>&#125;,<span class="function">()=&gt;</span>&#123;<span class="comment">/* functionB */</span>&#125;],</span><br><span class="line">  <span class="comment">//...</span></span><br><span class="line">])</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>好一点的写法是将处理逻辑函数进行缓存：</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="keyword">const</span> actions = <span class="function">()=&gt;</span>&#123;</span><br><span class="line">  <span class="keyword">const</span> functionA = <span class="function">()=&gt;</span>&#123;<span class="comment">/*do sth*/</span>&#125;</span><br><span class="line">  <span class="keyword">const</span> functionB = <span class="function">()=&gt;</span>&#123;<span class="comment">/*do sth*/</span>&#125;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Map</span>([</span><br><span class="line">    [&#123;<span class="attr">identity</span>:<span class="string">&#x27;guest&#x27;</span>,<span class="attr">status</span>:<span class="number">1</span>&#125;,functionA],</span><br><span class="line">    [&#123;<span class="attr">identity</span>:<span class="string">&#x27;guest&#x27;</span>,<span class="attr">status</span>:<span class="number">2</span>&#125;,functionA],</span><br><span class="line">    [&#123;<span class="attr">identity</span>:<span class="string">&#x27;guest&#x27;</span>,<span class="attr">status</span>:<span class="number">3</span>&#125;,functionA],</span><br><span class="line">    [&#123;<span class="attr">identity</span>:<span class="string">&#x27;guest&#x27;</span>,<span class="attr">status</span>:<span class="number">4</span>&#125;,functionA],</span><br><span class="line">    [&#123;<span class="attr">identity</span>:<span class="string">&#x27;guest&#x27;</span>,<span class="attr">status</span>:<span class="number">5</span>&#125;,functionB],</span><br><span class="line">    <span class="comment">//...</span></span><br><span class="line">  ])</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> onButtonClick = <span class="function">(<span class="params">identity,status</span>)=&gt;</span>&#123;</span><br><span class="line">  <span class="keyword">let</span> action = [...actions()].filter(<span class="function">(<span class="params">[key,value]</span>)=&gt;</span>(key.identity == identity &amp;&amp; key.status == status))</span><br><span class="line">  action.forEach(<span class="function">(<span class="params">[key,value]</span>)=&gt;</span>value.call(<span class="built_in">this</span>))</span><br><span class="line">&#125;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>这样写已经能满足日常需求了，但认真一点讲，上面重写了4次functionA还是有点不爽，假如判断条件变得特别复杂，比如identity有3种状态，status有10种状态，那你需要定义30条处理逻辑，而往往这些逻辑里面很多都是相同的，这似乎也是笔者不想接受的，那可以这样实现:</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="keyword">const</span> actions = <span class="function">()=&gt;</span>&#123;</span><br><span class="line">  <span class="keyword">const</span> functionA = <span class="function">()=&gt;</span>&#123;<span class="comment">/*do sth*/</span>&#125;</span><br><span class="line">  <span class="keyword">const</span> functionB = <span class="function">()=&gt;</span>&#123;<span class="comment">/*do sth*/</span>&#125;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Map</span>([</span><br><span class="line">    [<span class="regexp">/^guest_[1-4]$/</span>,functionA],</span><br><span class="line">    [<span class="regexp">/^guest_5$/</span>,functionB],</span><br><span class="line">    <span class="comment">//...</span></span><br><span class="line">  ])</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> onButtonClick = <span class="function">(<span class="params">identity,status</span>)=&gt;</span>&#123;</span><br><span class="line">  <span class="keyword">let</span> action = [...actions()].filter(<span class="function">(<span class="params">[key,value]</span>)=&gt;</span>(key.test(<span class="string">`<span class="subst">$&#123;identity&#125;</span>_<span class="subst">$&#123;status&#125;</span>`</span>)))</span><br><span class="line">  action.forEach(<span class="function">(<span class="params">[key,value]</span>)=&gt;</span>value.call(<span class="built_in">this</span>))</span><br><span class="line">&#125;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>这里Map的优势更加凸显，可以用正则类型作为key了，这样就有了无限可能，假如需求变成，凡是guest情况都要发送一个日志埋点，不同status情况也需要单独的逻辑处理，那我们可以这样写:</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="keyword">const</span> actions = <span class="function">()=&gt;</span>&#123;</span><br><span class="line">  <span class="keyword">const</span> functionA = <span class="function">()=&gt;</span>&#123;<span class="comment">/*do sth*/</span>&#125;</span><br><span class="line">  <span class="keyword">const</span> functionB = <span class="function">()=&gt;</span>&#123;<span class="comment">/*do sth*/</span>&#125;</span><br><span class="line">  <span class="keyword">const</span> functionC = <span class="function">()=&gt;</span>&#123;<span class="comment">/*send log*/</span>&#125;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Map</span>([</span><br><span class="line">    [<span class="regexp">/^guest_[1-4]$/</span>,functionA],</span><br><span class="line">    [<span class="regexp">/^guest_5$/</span>,functionB],</span><br><span class="line">    [<span class="regexp">/^guest_.*$/</span>,functionC],</span><br><span class="line">    <span class="comment">//...</span></span><br><span class="line">  ])</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> onButtonClick = <span class="function">(<span class="params">identity,status</span>)=&gt;</span>&#123;</span><br><span class="line">  <span class="keyword">let</span> action = [...actions()].filter(<span class="function">(<span class="params">[key,value]</span>)=&gt;</span>(key.test(<span class="string">`<span class="subst">$&#123;identity&#125;</span>_<span class="subst">$&#123;status&#125;</span>`</span>)))</span><br><span class="line">  action.forEach(<span class="function">(<span class="params">[key,value]</span>)=&gt;</span>value.call(<span class="built_in">this</span>))</span><br><span class="line">&#125;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>也就是说利用数组循环的特性，符合正则条件的逻辑都会被执行，那就可以同时执行公共逻辑和单独逻辑，因为正则的存在，你可以打开想象力解锁更多的玩法，本文就不赘述了。</p>
            <h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2>
            <p>本文已经教你了8种逻辑判断写法，包括：</p>
            <ol>
              <li>if/else</li>
              <li>switch</li>
              <li>一元判断时：存到Object里</li>
              <li>一元判断时：存到Map里</li>
              <li>多元判断时：将condition拼接成字符串存到Object里</li>
              <li>多元判断时：将condition拼接成字符串存到Map里</li>
              <li>多元判断时：将condition存为Object存到Map里</li>
              <li>多元判断时：将condition写作正则存到Map里</li>
            </ol>
            <p>至此，本文也将告一段落，愿你未来的人生里，不只是有if/else/switch。</p>
            <p><em><strong>如果你对本文感兴趣，请关注作者微信公众号：“大转转fe”</strong></em></p>
            <h1 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h1>
            <p><a target="_blank" rel="noopener" href="https://juejin.im/post/5bdfef86e51d453bf8051bf8">JavaScript 复杂判断的更优雅写法</a></p>

          </div>





          <footer class="post-footer">
            <div class="post-tags">
              <a href="/tags/JavaScript/" rel="tag"># JavaScript</a>
              <a href="/tags/%E5%A4%8D%E6%9D%82%E5%88%A4%E6%96%AD/" rel="tag"># 复杂判断</a>
            </div>



            <div class="post-nav">
              <div class="post-nav-item">
                <a href="/blob/2019-04-18-400-problems-with-nginx-configuration-reverse-proxy-or-jump/" rel="prev" title="nginx配置反向代理或跳转出现400问题">
                  <i class="fa fa-chevron-left"></i> nginx配置反向代理或跳转出现400问题
                </a>
              </div>
              <div class="post-nav-item">
                <a href="/blob/2019-05-23-overflow-scroll-element-on-ios-safari-browser-cannot-slide/" rel="next" title="iOS Safari浏览器上 overflow scroll 元素无法滑动">
                  iOS Safari浏览器上 overflow scroll 元素无法滑动 <i class="fa fa-chevron-right"></i>
                </a>
              </div>
            </div>
          </footer>
        </article>
      </div>







      <script>
        window.addEventListener('tabs:register', () => {
          let {
            activeClass
          } = CONFIG.comments;
          if (CONFIG.comments.storage) {
            activeClass = localStorage.getItem('comments_active') || activeClass;
          }
          if (activeClass) {
            const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
            if (activeTab) {
              activeTab.click();
            }
          }
        });
        if (CONFIG.comments.storage) {
          window.addEventListener('tabs:click', event => {
            if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
            const commentClass = event.target.classList[1];
            localStorage.setItem('comments_active', commentClass);
          });
        }
      </script>
    </div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


      <div class="copyright">
        &copy;
        <span itemprop="copyrightYear">2021</span>
        <span class="with-love">
          <i class="fa fa-heart"></i>
        </span>
        <span class="author" itemprop="copyrightHolder">holidaypenguin</span>
      </div>
      <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/mist/" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a> 强力驱动
      </div>

    </div>
  </footer>


  <script size="300" alpha="0.1" zIndex="-1" src="https://cdn.jsdelivr.net/npm/ribbon.js@1.0.2/dist/ribbon.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
  <script src="/js/love.js"></script>

  <script src="/js/development.js"></script>
  <script src="/js/utils.js"></script>
  <script src="/js/motion.js"></script>
  <script src="/js/schemes/muse.js"></script>
  <script src="/js/next-boot.js"></script>


  <script src="/js/local-search.js"></script>









  <script>
    (function() {
      function leancloudSelector(url) {
        url = encodeURI(url);
        return document.getElementById(url).querySelector('.leancloud-visitors-count');
      }

      function addCount(Counter) {
        const visitors = document.querySelector('.leancloud_visitors');
        const url = decodeURI(visitors.id);
        const title = visitors.dataset.flagTitle;

        Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({
            url
          })))
          .then(response => response.json())
          .then(({
            results
          }) => {
            if (results.length > 0) {
              const counter = results[0];
              leancloudSelector(url).innerText = counter.time + 1;
              Counter('put', '/classes/Counter/' + counter.objectId, {
                  time: {
                    '__op': 'Increment',
                    'amount': 1
                  }
                })
                .catch(error => {
                  console.error('Failed to save visitor count', error);
                });
            } else {
              Counter('post', '/classes/Counter', {
                  title,
                  url,
                  time: 1
                })
                .then(response => response.json())
                .then(() => {
                  leancloudSelector(url).innerText = 1;
                })
                .catch(error => {
                  console.error('Failed to create', error);
                });
            }
          })
          .catch(error => {
            console.error('LeanCloud Counter Error', error);
          });
      }

      function showTime(Counter) {
        const visitors = document.querySelectorAll('.leancloud_visitors');
        const entries = [...visitors].map(element => {
          return decodeURI(element.id);
        });

        Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({
            url: {
              '$in': entries
            }
          })))
          .then(response => response.json())
          .then(({
            results
          }) => {
            for (let url of entries) {
              const target = results.find(item => item.url === url);
              leancloudSelector(url).innerText = target ? target.time : 0;
            }
          })
          .catch(error => {
            console.error('LeanCloud Counter Error', error);
          });
      }

      const {
        app_id,
        app_key,
        server_url
      } = {
        "enable": true,
        "app_id": "povuqNsSqFodlakVIwtEX5kb-gzGzoHsz",
        "app_key": "zXD40RDtDB3DMtpC89k0AK7g",
        "server_url": null,
        "security": false
      };

      function fetchData(api_server) {
        const Counter = (method, url, data) => {
          return fetch(`${api_server}/1.1${url}`, {
            method,
            headers: {
              'X-LC-Id': app_id,
              'X-LC-Key': app_key,
              'Content-Type': 'application/json',
            },
            body: JSON.stringify(data)
          });
        };
        if (CONFIG.page.isPost) {
          if (CONFIG.hostname !== location.hostname) return;
          addCount(Counter);
        } else if (document.querySelectorAll('.post-title-link').length >= 1) {
          showTime(Counter);
        }
      }

      const api_server = app_id.slice(-9) === '-MdYXbMMI' ? `https://${app_id.slice(0, 8).toLowerCase()}.api.lncldglobal.com` : server_url;

      if (api_server) {
        fetchData(api_server);
      } else {
        fetch('https://app-router.leancloud.cn/2/route?appId=' + app_id)
          .then(response => response.json())
          .then(({
            api_server
          }) => {
            fetchData('https://' + api_server);
          });
      }
    })();
  </script>



<script>
            window.imageLazyLoadSetting = {
                isSPA: false,
                preloadRatio: 1,
                processImages: null,
            };
        </script><script>window.addEventListener("load",function(){var t=/\.(gif|jpg|jpeg|tiff|png)$/i,r=/^data:image\/[a-z]+;base64,/;Array.prototype.slice.call(document.querySelectorAll("img[data-original]")).forEach(function(a){var e=a.parentNode;"A"===e.tagName&&(e.href.match(t)||e.href.match(r))&&(e.href=a.dataset.original)})});</script><script>!function(n){n.imageLazyLoadSetting.processImages=o;var e=n.imageLazyLoadSetting.isSPA,i=n.imageLazyLoadSetting.preloadRatio||1,r=Array.prototype.slice.call(document.querySelectorAll("img[data-original]"));function o(){e&&(r=Array.prototype.slice.call(document.querySelectorAll("img[data-original]")));for(var t,a=0;a<r.length;a++)0<=(t=(t=r[a]).getBoundingClientRect()).bottom&&0<=t.left&&t.top<=(n.innerHeight*i||document.documentElement.clientHeight*i)&&function(){var t,e,n,i,o=r[a];t=o,e=function(){r=r.filter(function(t){return o!==t})},n=new Image,i=t.getAttribute("data-original"),n.onload=function(){t.src=i,e&&e()},t.src!==i&&(n.src=i)}()}o(),n.addEventListener("scroll",function(){var t,e;t=o,e=n,clearTimeout(t.tId),t.tId=setTimeout(function(){t.call(e)},500)})}(this);</script></body>

</html>